const app=getApp()
const userDB=wx.cloud.database().collection("user")
const messageDB=wx.cloud.database().collection("Message")
const recordsDB=wx.cloud.database().collection("records")
var friendOpenid
var friendTime

Page({
  data: {
    nickName:"",
    image:"",
    friendName:"",
    friendImage:"",
    timestamp:'',
    datalist:[],
    friendDay:"",
    flag:"",
    ifkong:false,
  },

  onLoad: function () {
    var that=this
    userDB.where({
      _openid:app.globalData.openid
    }).get({
      success:res=> {
        friendOpenid=res.data[0].friend
        friendTime=res.data[0].friendTime
        that.setData({
          nickName:res.data[0].nickName,
          image:res.data[0].avatarUrl,
        })

        userDB.where({
          _openid:friendOpenid
        }).get({
          success:res=>{
            that.setData({
              friendName:res.data[0].nickName,
              friendImage:res.data[0].avatarUrl,
            })
          }
        })
        //显示用户和病友结对的天数
        var curtime = Date.parse(new Date());
        this.intervalTime(friendTime,curtime)
        this.getDakaDay()

        messageDB.where({
          receiveOpenid:app.globalData.openid
        }).get({
          success:res=>{
            console.log("看以下ifkong",that.data.ifkong)
            console.log("看一下好友信息的",res.data.length)
            if(res.data.length==0){
            that.setData({
              ifkong:true,
            })
            }else{
              that.setData({
                datalist:res.data,
                ifkong:false,
              })
            }
          }
        })
      },
      fail:res=>{
        console.log("查询数据失败",res)
      } 
    })
  },

  sendMessage(){
    let that=this
    that.getTime()
    console.log("看一下sendMessage里的flag",that.data.flag)
    if(that.data.flag==0){
      messageDB.add({
        data:{
          sendOpenid:app.globalData.openid,
          receiveOpenid:friendOpenid,
          content:"今天要记得去打卡呀,一定要坚持呀",
          timestamp:that.data.timestamp,
        }
      })
      wx.showToast({
        title: '发送成功',
        icon: 'succes',
        duration: 1000,
        mask:true
    })
      //为勋章墙添加提醒记录
      recordsDB.where({
        _openid:app.globalData.openid
      }).update({
        data:{
          remind:remind+1
        }
      })
    }else{
      messageDB.add({
        data:{
          sendOpenid:app.globalData.openid,
          receiveOpenid:friendOpenid,
          content:"每天坚持下去，大家一起再接再励吧",
          timestamp:this.data.timestamp,
        }
      })
      wx.showToast({
        title: '发送信息成功',
        icon: 'succes',
        duration: 1000,
        mask:true
    })
      //为勋章墙添加鼓励记录
      recordsDB.where({
        _openid:app.globalData.openid
      }).update({
        data:{
          encourage:encourage+1
        }
      })
    }
  },


  getTime:function(){
    var curtime = Date.parse(new Date());
    curtime = curtime / 1000;
    //获取当前时间  
    var n = curtime * 1000;
    var date = new Date(n);
    //年，月，日，时，分，秒
    var Y = date.getFullYear();
    var M = (date.getMonth() + 1 < 10 ? '0' + (date.getMonth() + 1) : date.getMonth() + 1);
    var D = date.getDate() < 10 ? '0' + date.getDate() : date.getDate();
    var h = date.getHours();
    var m = date.getMinutes();
    var s = date.getSeconds();
    this.data.timestamp=Y +'/'+ M+'/' + D +' '+ h + ":" + m + ":" + s
  },

  deleteFriend(){
    userDB.where(_.or([{
      _openid:app.globalData.openid
    },{
      _openid:friendOpenid
    }
    ])).update({
      data:{
        friend:"0",
        friendTime:0,
      }
    })

    messageDB.where({
      receiveOpenid:app.globalData.openid
    }).remove().then(res=>{
      console.log(res)
    })

  },

  intervalTime(startTime,endTime){
    let that=this
    var difValue=(endTime-startTime)/(1000*60*60*24);
    var days=parseInt(difValue);
    that.setData({
      friendDay:days
    })
  },

  getDakaDay(){
    let that=this
    that.setData({
      flag:0
    })
    console.log("初始化flag现在是多少",that.data.flag)
    wx.cloud.callFunction({
      name:'clockIn',
      data:{
        type:"getRecords",
        openid:friendOpenid
      },
      complete:res=>{
        var tempRecords = res.result.records
        //求当前时间的年、月、日
        var today=Date.parse(new Date())
        today=today/1000
        var n=today*1000
        var date=new Date(n)
        var year=date.getFullYear()
        var month=(date.getMonth() + 1 < 10 ? '0' + (date.getMonth() + 1) : date.getMonth() + 1)
        var day = date.getDate() < 10 ? '0' + date.getDate() : date.getDate();
        
        for(var j=0;j<tempRecords.length;j++){
          var _record=Date.parse(tempRecords[j]._date)
          _record=_record/1000
          var _n=_record*1000
          var _date=new Date(_n)
          var _year=_date.getFullYear()
          var _month=(_date.getMonth() + 1 < 10 ? '0' + (_date.getMonth() + 1) : _date.getMonth() + 1)
          var _day = _date.getDate() < 10 ? '0' + _date.getDate() : _date.getDate();
          if(year==_year&&month==_month){
            if(day==_day){
              that.setData({
                flag:1
              })
              break
            }
          }
        }
      }
    })
  },

  onPullDownRefresh:function(){
    wx.showNavigationBarLoading() //在标题栏中显示加载
    this.onLoad()
    //模拟加载
    setTimeout(function(){
      //complete
      wx.hideNavigationBarLoading() //完成停止加载
      wx.stopPullDownRefresh() //停止下拉刷新
    },1500);
  },

})